package com.cy.xrd.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cy.xrd.core.mapper.DictMapper;
import com.cy.xrd.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @title: ExcelEictDTOListener
 * @Author Luo
 * @Date: 2021/7/12 下午 12:51
 * @Version 1.0
 */
@Slf4j
@NoArgsConstructor
public class ExcelEictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private DictMapper dictMapper;

    //数据列表
    List<ExcelDictDTO> list = new ArrayList<>();

    //每隔5条记录批量存储一次数据
    private static final int BATCH_COUNT = 5;

    public ExcelEictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        log.info("解析到一条记录:{}", excelDictDTO);
        //将数据存入数据列表
        list.add(excelDictDTO);
        if (list.size() >= BATCH_COUNT) {
            SaveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //当最后剩余的数据记录数不足BATCH_COUNT是,我们最终一次性存储剩余数据
        SaveData();
        log.info("所有数据解析完成!");
    }

    private void SaveData() {
        log.info("{} 条数被存储到数据库......", list.size());
        //调用mapper层的批量save方法:save list对象
        dictMapper.insertBatch(list);
        log.info("{} 条数被存储到数据库成功!", list.size());
    }
}